import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Checkbox } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import DataForm from './components/DataForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';

const tableId = uniqueId('tauTable-');

function CompanyInfo() {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const { companyStore: store } = useStore();
  const companyRef = useRef();

  useEffect(() => {
    (async () => {
      await store.getPayMerchant();
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { registerAddr, status, getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      registerAddr,
      status,
      from,
      to,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    setModal({
      show: 'add',
      record: null,
    });
  };

  // 点击打开查看
  const handleOpenView = (company) => {
    setModal({
      show: 'view',
      record: company,
    });
  };

  // 点击打开编辑
  const handleOpenEdit = (company) => {
    setModal({
      show: 'add',
      record: company,
    });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal(null);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`承运商创建成功` });
      } catch (e) {
        Message.error({ content: t`承运商创建失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const reader = new FileReader();
    reader.onloadend = async () => {
      try {
        await RSocket.rc({
          route: 'files.upload',
          args: {
            binary: {
              binaryId: companyRef.current?.id,
              mimeType: file.type,
              filename: file.name,
            },
          },
          data: Buffer.from(reader.result),
        });
        onSuccess();
      } catch (e) {
        onError(e);
        Message.warning('上传失败');
      } finally {
        // eslint-disable-next-line no-undef
      }
    };
    reader.readAsArrayBuffer(file);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeChannel',
            title: t`添加承运商`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'registerAddr',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.cityName),
              placeholder: t`注册地区`,
            },
          },
          {
            name: 'status',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.statusName),
              placeholder: t`启用状态`,
            },
          },
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始更新时间`, t`结束更新时间`],
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.company)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', { width: 78, cell: (v, _, company) => <Button type="primary" text onClick={() => handleOpenView(company)}>{v}</Button> }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 200,
              cell: (_, __, trip) => {
                const list = [
                  {
                    title: t`编辑`,
                    onClick: () => handleOpenEdit(trip),
                  },
                ];
                return (
                  <MoreFuncDropDown dropdownItems={list} maxShow={2} />
                );
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal?.show === 'add' || modal?.show === 'edit' || modal?.show === 'view'}
        // eslint-disable-next-line no-nested-ternary
        title={modal?.show === 'add' ? t`添加承运商` : t`编辑承运商`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="90%"
      >
        <DataForm
          companyId={companyRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal?.show === 'add' ? handleCreate : handleUpdate}
          handleCustomRequest={handleCustomRequest}
        />
      </Drawer>
    </TauPage>
  );
}

export default observer(CompanyInfo);
